package com.alaoks.uploadfile.controller;


import com.alaoks.uploadfile.entity.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
public class DownloadController {
    @GetMapping("/download/{dir}/{filename}")
    public void download(
            @PathVariable("dir") String dir,
            @PathVariable("filename") String filename,
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse
    ){
        //跟路径
        String rootPath="/spb/csupload/";
        File file=new File(rootPath+dir+"/"+filename);
        if(file.exists()){
            httpServletResponse.setContentType("application/force-download");
            httpServletResponse.addHeader("Content-Disposition","attachment;filename="+filename);
            byte[] buffer=new byte[1024];
            try(FileInputStream fis=new FileInputStream(file)) {
                try (BufferedInputStream bis=new BufferedInputStream(fis)){
                    OutputStream os=httpServletResponse.getOutputStream();
                    int i=bis.read(buffer);
                    while (i!=-1){
                        os.write(buffer,0,i);
                        i=bis.read(buffer);
                    }
                    os.close();
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
